import 'dart:convert';
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:private_journey/GlobalInfo.dart';
import 'package:private_journey/States.dart';
import 'package:private_journey/pages/trending.dart';
import 'package:private_journey/services/DbService.dart';
import 'package:private_journey/services/FileService.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shadcn;
import 'package:signals/signals_flutter.dart';

class AddNewIconPage extends StatefulWidget {
  final LinkInfo? e;

  const AddNewIconPage({super.key, this.e});

  @override
  State<StatefulWidget> createState() {
    return AddNewIconPageState();
  }
}

class AddNewIconPageState extends State<AddNewIconPage> {
  final shadcn.FormController controller = shadcn.FormController();
  shadcn.TextEditingController c1 = shadcn.TextEditingController();
  shadcn.TextEditingController c2 = shadcn.TextEditingController();

  Widget buildIconFile(String file) {
    var fileBase64 = base64Encode(File(file).readAsBytesSync());

    if (FileService.isSvg(fileBase64)) {
      return SvgPicture.file(File(file), height: 50, width: 50);
    }
    if (FileService.isPng(fileBase64)) {
      return Image.file(File(file), height: 50, width: 50);
    }
    if (FileService.isIco(fileBase64)) {
      return Image.file(File(file), height: 50, width: 50);
    }
    throw Exception('not support file type');
  }

  @override
  void initState() {
    super.initState();
    if (widget.e != null) {
      c1.text = widget.e!.text;
      c2.text = widget.e!.url;
    }
  }

  @override
  void dispose() {
    logger.i('add new icon page dispose');
    controller.dispose();
    c1.dispose();
    c2.dispose();
    currentLinkIcon.value = '';
    super.dispose();
  }

  Widget buildIcon(LinkInfo e) {
    if (FileService.isSvg(e.icon)) {
      var icon = base64Decode(e.icon);
      return SvgPicture.memory(icon, height: 50, width: 50);
    }
    if (FileService.isPng(e.icon)) {
      var icon = base64Decode(e.icon);
      return Image.memory(icon, height: 50, width: 50);
    }
    if (FileService.isIco(e.icon)) {
      var icon = base64Decode(e.icon);
      return Image.memory(icon, height: 50, width: 50);
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shadowColor: shadcn.Colors.pink,
      title: const Text('Add Link'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Make changes to your profile here. Click save when you\'re done',
          ),
          const shadcn.Gap(16),
          ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 400),
            child: shadcn.Form(
              controller: controller,
              child: shadcn.FormTableLayout(
                rows: [
                  shadcn.FormField<String>(
                    key: shadcn.FormKey(#icon),
                    label: Text('Icon'),
                    child: Watch((context) {
                      return shadcn.SecondaryButton(
                        onPressed: () async {
                          var file = await FilePicker.platform.pickFiles(
                            allowMultiple: false,
                          );
                          currentLinkIcon.value = file!.paths[0]!;
                        },
                        shape: shadcn.ButtonShape.circle,
                        child:
                            currentLinkIcon.value == ''
                                ? (widget.e == null
                                    ? Icon(Icons.add)
                                    : buildIcon(widget.e!))
                                : buildIconFile(currentLinkIcon.value),
                      );
                    }),
                  ),
                  shadcn.FormField<String>(
                    key: const shadcn.FormKey(#linkname),
                    label: const Text('Link Name'),
                    child: shadcn.TextField(controller: c1),
                  ),
                  shadcn.FormField<String>(
                    key: shadcn.FormKey(#linkurl),
                    label: Text('Link Url'),
                    child: shadcn.TextField(controller: c2),
                  ),
                ],
              ),
            ).withPadding(vertical: 16),
          ),
        ],
      ),
      actions: [
        shadcn.PrimaryButton(
          child: const Text('Save Link'),
          onPressed: () async {
            // Navigator.of(context).pop(controller.values);
            var f = File(currentLinkIcon.value);
            var b64Str = base64Encode(f.readAsBytesSync());

            DbService dbService = DbService();
            var db = await dbService.database;
            db.rawInsert(
              'insert into my_sites (icon_url, site_name, site_url) values (?,?,?)',
              [
                b64Str,
                controller.values[shadcn.FormKey(#linkname)],
                controller.values[shadcn.FormKey(#linkurl)],
              ],
            );
            linkInfos.value = [
              ...linkInfos.value,
              LinkInfo(
                id: -1,
                icon: b64Str,
                text: controller.values[shadcn.FormKey(#linkname)],
                url: controller.values[shadcn.FormKey(#linkurl)],
              ),
            ];
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }
}
